﻿#include "DiolDeviceManager.h"

#include <assert.h>
#include <map>
#include <sstream>
#include <string.h>

class DebugDeviceListener : public Diol::Device::Listener
{
public:
	virtual void onObjectChanged( Diol::Device* device, Diol::Object* object )
	{
		printf( "Object changed - %s\n", object->toString().c_str() );
	}
};

class DebugDeviceManagerListener : public Diol::DeviceManager::Listener
{
public:
	virtual void onDeviceConnected( Diol::DeviceManager* deviceManager, Diol::Device* device )
	{
		printf( "Device connected - %s\n", device->getDeviceInstance().getInstanceName().c_str() );
		
		// Create a listener for the Device, register it and remember it
		Diol::Device::Listener* listener = new DebugDeviceListener();
		mListeners.insert( std::make_pair( device, listener ) );
		device->addListener( listener );
	}

	virtual void onDeviceDisconnecting( Diol::DeviceManager* deviceManager, Diol::Device* device )
	{
		printf( "Device disconnecting - %s\n", device->getDeviceInstance().getInstanceName().c_str() );
		
		// Retrieve the listener we created for the Device, unregister it, delete it and forget it
		std::map<Diol::Device*, Diol::Device::Listener*>::iterator itr = mListeners.find( device );
		assert( itr!=mListeners.end() );
		Diol::Device::Listener* listener = (*itr).second;
		device->removeListener( listener );
		mListeners.erase( itr );
		delete listener;
	}

private:
	std::map<Diol::Device*, Diol::Device::Listener*> mListeners;	
};

std::string deviceToString( const Diol::Device* device )
{
	std::stringstream stream;
	stream << "Device:\n";
	stream << " InstanceName:'" << device->getDeviceInstance().getInstanceName() << "'\n";
	stream << " ProductName:'" << device->getDeviceInstance().getProductName() << "'\n";
	stream << " DeviceType:" << device->getDeviceInstance().getDeviceType() << "\n";
	stream << " DeviceSubType:" << device->getDeviceInstance().getDeviceSubType() << "\n";
	stream << " Objects:\n";
	const Diol::Objects& objects = device->getObjects();
	for ( std::size_t i=0; i<objects.size(); ++i )
	{
		const Diol::Object* object = objects[i];
		stream << "  " << object->toString() << "\n";
	}
	return stream.str();
}

std::string devicesToString( const Diol::DeviceManager& manager )
{
	std::stringstream stream;
	const Diol::DeviceManager::DeviceList& devices =  manager.getDevices();
	for ( std::size_t i=0; i<devices.size(); ++i )
	{
		Diol::Device* device = devices[i].second;
		stream << deviceToString( device );
	}
	return stream.str();
}

int main()
{
	Diol::DeviceManager manager(true, true);
	manager.addListener( new DebugDeviceManagerListener() );
	int i = 0;
	while ( i!=30 )
	{
		manager.update();
		Sleep(500);
		//printf("%s", devicesToString( manager ).c_str() );
		i++;
	}
	return 0;
}
